package distance;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;

public class Caculate {
	/** 
     * 通过经纬度获取距离(单位：米) 
     * @param start 
     * @param end 
     * @return 
     */  
    public static double distance(LatLng start,LatLng end) {  
        double radLat1 = rad(start.getLat());  
        double radLat2 = rad(end.getLat());  
        double a = radLat1 - radLat2;  
        double b = rad(start.getLng()) - rad(end.getLng());  
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)  
                + Math.cos(radLat1) * Math.cos(radLat2)  
                * Math.pow(Math.sin(b / 2), 2)));  
        s = s * Config.EARTH_RADIUS;  
        s = Math.round(s * 10000d) / 10000d;  
        s = s*1000;  
        return s;  
    }
    
    /**
     * 从集合中获取最近的那些点
     * @Title nestest
     * @Description  返回值的getNearest
     * @param origin
     * @param ranges
     * @param scope 半径
     * @return
     * @throws TODO
     */
    public static List<LatLng> nestest(LatLng origin,List<LatLng> ranges,double scope) {
    	List<LatLng> dis=new ArrayList<LatLng>();
    	for (int i = 0; i < ranges.size(); i++) {
    		double distance=distance(origin, ranges.get(i));
    		if(scope>=distance){
    			origin.setDistance(Integer.MAX_VALUE);
    			origin.setDistance(distance);
    			origin.setNearest(new LatLng(ranges.get(i).getLat(), ranges.get(i).getLng(), distance, origin)); 
    			
    			dis.add(origin);
    		}
		}

    	
        return dis;
    }
    
    /**
     * 从集合中获取最近的那个点
     * @Title nestest
     * @Description  返回值的getNearest
     * @param origin
     * @param ranges
     * @return
     * @throws TODO
     */
    public static LatLng nestest(LatLng origin,List<LatLng> ranges) {
    	List<Double> dis=new ArrayList<Double>();
    	for (int i = 0; i < ranges.size(); i++) {
    		dis.add(distance(origin, ranges.get(i)));
		}
    	
    	Double distance=Collections.min(dis);   	
    	int index=dis.indexOf(distance);
    	origin.setNearest(ranges.get(index));
    	
        return origin;
    }
	
	private static double rad(double d) {  
        return d * Math.PI / 180.0;  
    }  
  
    
}
